/**
 * Copyright (c) 2011 ~ 2015 Deepin, Inc.
 *               2013 ~ 2015 jouyouyun
 *
 * Author:      jouyouyun <jouyouwen717@gmail.com>
 * Maintainer:  jouyouyun <jouyouwen717@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 **/

package keybindings

import (
	"./shortcuts"
	"fmt"
)

func (m *Manager) Reset() {
}

func (m *Manager) GrabKeyboardAndMouse() {
}

func (m *Manager) ListShortcuts() shortcuts.Shortcuts {
	list := shortcuts.ListWMShortcuts()
	list = append(list, m.grabedList...)
	return list
}

func (m *Manager) AddShortcut(name, action string, accel string) (bool, string, error) {
	avaliable, conflict := m.CheckAvaliable(accel)
	if !avaliable {
		return avaliable, conflict, nil
	}

	id := shortcuts.AddCustomShortcut(name, action, []string{accel})
	return m.ModifiedAccel(id, shortcuts.KeyTypeCustom, accel, true)
}

func (m *Manager) DeleteShortcut(id string, ty int32) error {
	if ty != shortcuts.KeyTypeCustom {
		return fmt.Errorf("Invalid shortcut type '%v'", ty)
	}

	s := m.grabedList.GetById(id, ty)
	if s == nil {
		return fmt.Errorf("Invalid shortcut id '%s'", id)
	}

	shortcuts.DeleteCustomShortcut(id)
	m.ungrabShortcut(s)
	return nil
}

func (m *Manager) ModifiedAccel(id string, ty int32, accel string, grabed bool) (bool, string, error) {
	s := m.grabedList.GetById(id, ty)
	if s == nil {
		return false, "", fmt.Errorf("Invalid id '%s' or type '%v'",
			id, ty)
	}

	if !grabed {
		m.ungrabShortcut(s)
		s.DeleteAccel(accel)
		return true, "", nil
	}

	avaliable, conflict := m.CheckAvaliable(accel)
	if !avaliable {
		return avaliable, conflict, nil
	}

	s.AddAccel(accel)
	err := m.grabShortcut(s)
	if err != nil {
		return false, "", err
	}

	return true, "", nil
}

func (m *Manager) CheckAvaliable(accel string) (bool, string) {
	list := m.ListShortcuts()
	s := list.GetByAccel(accel)
	if s == nil {
		return true, ""
	}

	return false, s.Id
}
